<template>
  <div class="flex h-full">
    <div class="absolute top-[-9999px] hidden">
      <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
      <PrintView id="printMe" :print-data="printData" />
    </div>
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px' }">
      <SideList ref="sideListRef" @change="onSideListChange" />
    </a-card>

    <div class="flex flex-col flex-1 overflow-hidden">
      <a-card>
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <a-form-item label="样本号" class="mb-0">
              <a-input-group compact>
                <a-input v-model:value="store.recordCode" placeholder="请输入" style="width: calc(100% - 60px)" @keydown.enter="store.getOrderData(1)" />
                <a-button @click="store.getOrderData()"><SyncOutlined /></a-button>
              </a-input-group>
            </a-form-item>
            <a-form-item class="mb-0 mr-3">
              <a-date-picker v-model:value="store.recordDate" class="w-full" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </a-form-item>
            <a-space>
              <a-button type="primary" :disabled="!store.currentPatient.lsh" @click="onSave(true)">保存并下一个</a-button>
              <a-button @click="onChangeRecordCode(0)">上一个</a-button>
              <a-button @click="onChangeRecordCode(1)">下一个</a-button>
              <a-button type="primary" :disabled="!store.currentPatient.lsh" @click="onSave(false)">保存</a-button>
            </a-space>
          </div>
          <a-space>
            <a-button type="primary" :disabled="!store.currentPatient.lsh" @click="onCheck">{{
              store.currentPatient.status === '1' ? '撤销审核' : '审核'
            }}</a-button>
            <a-button :disabled="!store.currentPatient.lsh" @click="onPrint(1)">预览</a-button>
            <a-button :disabled="!store.currentPatient.lsh" @click="onPrint(2)">打印</a-button>

            <a-button danger ghost @click="onDelete">删除</a-button>
          </a-space>
        </div>
      </a-card>
      <PatientInfoHeader :patient-info="store.currentPatient" class="mt-2" @change="sideListRef.getSideData()">
        <template #prefix>
          <a-form-item label="条形码" class="mb-0 mr-2">
            <SelectTable
              v-model:value="store.barCode"
              placeholder="条形码/姓名/助记码"
              type="检验条码"
              :row-disabled="(row) => !row.barCode"
              :search-params="getSearchParams()"
              @select="onSelectCode"
            />
          </a-form-item>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="卡号" :width="200" :value="store.currentPatient.brId" />
            <LabelValue label="科室" :width="200" :value="store.currentPatient.applyDeptName" />
            <LabelValue label="医师" :width="200" :value="store.currentPatient.applyDoctorName" />
            <LabelValue label="挂号时间" :width="200" :value="store.currentPatient.ghsj" />
          </div>
          <div class="flex items-center">
            <LabelValue v-if="store.currentPatient.applyPath === 0" label="门诊号" :width="200" :value="store.currentPatient.key" />
            <LabelValue v-if="store.currentPatient.applyPath === 1" label="床位号" :width="200" :value="store.currentPatient.lastBedCode" />
            <LabelValue label="项目" :width="360" :value="store.currentPatient.items" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex justify-between mt-2 flex-1" :class="{ 'full-disabled': store.isDisabled }">
        <a-card class="w-[400px] mr-2" :loading="store.isLoading">
          <BaseTitle class="" title="检验信息" />
          <a-form :model="store.currentData.lisRecord" class="w-full pr-2" :label-col="{ style: { width: '78px' } }">
            <a-form-item label="诊断">
              <a-tooltip
                v-if="store.currentData.lisRecord.diagnosisName?.length > 15"
                :title="store.currentData.lisRecord.diagnosisName"
                placement="topLeft"
                :mouse-enter-delay="0.6"
              >
                <div class="w-full truncate">
                  {{ store.currentData.lisRecord.diagnosisName || '-' }}
                </div>
              </a-tooltip>
              <template v-else>
                {{ store.currentData.lisRecord.diagnosisName || '-' }}
              </template>
            </a-form-item>
            <a-form-item label="样本类型">
              <SelectItem v-model:value="store.currentData.lisRecord.recordType" type="DT00261" placeholder="请选择" />
            </a-form-item>

            <a-form-item label="申请医生">
              <SelectTable v-model:value="store.currentData.lisApply.applyDoctorName" type="医生" placeholder="请选择" @select="onSelectApplyDoctor" />
            </a-form-item>
            <a-form-item label="申请时间">
              <a-date-picker
                v-model:value="store.currentData.lisApply.applyTime"
                show-time
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </a-form-item>
            <a-form-item label="采样时间">
              <a-date-picker
                v-model:value="store.currentData.lisRecord.recordTime"
                show-time
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </a-form-item>
            <a-form-item label="验收时间">
              <a-date-picker
                v-model:value="store.currentData.lisRecord.acceptanceTime"
                show-time
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </a-form-item>
            <a-form-item label="检验师">
              <SelectTable
                v-model:value="store.currentData.lisRecord.testEmpName"
                type="医生"
                :search-params="{ emplb: '7' }"
                placeholder="请选择"
                @select="onSelectTestDoctor"
              />
            </a-form-item>
            <a-form-item label="检验时间">
              <a-date-picker
                v-model:value="store.currentData.lisRecord.testTime"
                show-time
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </a-form-item>

            <a-form-item label="审核人">
              <!-- <a-input v-model:value="" placeholder="请输入" /> -->
              {{ store.currentData.lisRecord.auditName || '-' }}
            </a-form-item>
            <a-form-item label="审核时间">
              {{ store.currentData.lisRecord.auditTime || '-' }}
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea v-model:value="store.currentData.lisRecord.memo" :rows="5" placeholder="请输入" />
            </a-form-item>
          </a-form>
        </a-card>
        <DataTable @save="onSave" />
        <a-card class="w-72 ml-2 history-card" :class="historyExpand ? 'history-expand' : ''" :body-style="{ paddingTop: 0 }">
          <div class="history-expand-btn" @click="() => (historyExpand = !historyExpand)">
            <DoubleLeftOutlined v-if="historyExpand" />
            <DoubleRightOutlined v-else />
          </div>
          <div v-if="historyExpand" class="pt-12 text-primary font-semibold">历史</div>
          <!-- v-model:activeKey="leftActiveKey" -->
          <a-tabs centered>
            <a-tab-pane key="1">
              <template #tab>
                <div class="px-5 text-center">历史</div>
              </template>
              <div class="overflow-auto" style="height: calc(100vh - 260px)">
                <!-- @success="onCopySuccess" -->
                <HistoryCase :open="historyExpand" />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
    <!-- <CrisisModal v-model:open="crisisOpen" @success="onCrisisSuccess" /> -->
    <CrisisModal v-model:open="crisisOpen" :list-data="crisisList" @success="onFetchCheck()" />
  </div>
</template>

<script setup>
import { ref, onUnmounted, onMounted, watch } from 'vue'
import { SyncOutlined, DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { chunk } from 'lodash-es'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import PrintView from '@/views/workstation-inspect/report/PrintView.vue'
import SideList from './components/SideList.vue'
import CrisisModal from './components/CrisisModal.vue'
import DataTable from './components/DataTable.vue'
import HistoryCase from './components/HistoryCase.vue'
import useStore from './store'

const { empId, empName } = useUserStore()
const printData = ref({})
const printMe = ref()
const sideListRef = ref(null)
const historyExpand = ref(true)
const crisisOpen = ref(false) // 危
const crisisList = ref([])
const sideListParams = ref({})
const store = useStore()
const onSideListChange = (data) => {
  sideListParams.value = data
}
const onCheck = () => {
  crisisList.value = []
  if (store.currentData.lisRecord.crisisStatus === '1' && store.currentPatient.status !== '1') {
    crisisOpen.value = true
    crisisList.value = store.currentData.lisRecordItemList.filter((item) => item.crisisStatus === '1')
  } else {
    onFetchCheck()
  }
}
// 审核
const onFetchCheck = async () => {
  if (store.currentPatient.status !== '1') {
    const params = constructData()
    await post('/lis/LisRecord/doSaveLisRecord', params)
  }
  message.loading('审核中...', 1)
  await new Promise((resolve) => setTimeout(resolve, 1000))
  const url = store.currentPatient.status === '1' ? '/lis/LisRecord/doCancelAuditLisRecord' : '/lis/LisRecord/doAuditLisRecord'
  const { code } = await post(url, { lisApplyLshList: [store.currentPatient.lsh] })
  if (code !== 0) return message.error('保存失败')
  message.success('保存成功')
  sideListRef.value.getSideData()
  store.getOrderData()
}

const onSelectApplyDoctor = (selected) => {
  store.currentData.lisApply.applyDoctorId = selected.empId
  store.currentData.lisApply.applyDoctorName = selected.empName
}
const onSelectTestDoctor = (selected) => {
  store.currentData.lisRecord.testEmpId = selected.empId
  store.currentData.lisRecord.testEmpName = selected.empName
}
//构造数据
const constructData = () => {
  const params = { ...store.currentData }
  params.lisRecord.instrumentId = store.currentInstrument.id
  params.lisRecord.recordCode = store.recordCode
  params.recordDate = store.recordDate.replace(/-/g, '') || undefined
  params.lisRecordItemList.forEach((item) => {
    item.referValue = item.minValue + '~' + item.maxValue
    item.tips = 0
    Number(item.testResult) < Number(item.minValue) && (item.tips = 2)
    Number(item.testResult) > Number(item.maxValue) && (item.tips = 1)
  })
  return params
}

const onSave = async (isNext = false) => {
  const params = constructData()
  const { code, msg } = await post('/lis/LisRecord/doSaveLisRecord', params)
  if (code !== 0) return message.error(msg || '请求失败')
  message.success(msg || '保存成功')
  // store.reset()
  // store.getSampleNumber()
  sideListRef.value.getSideData()
  isNext && onChangeRecordCode(1)
}
const onDelete = async () => {
  if (store.currentPatient?.status === '1') {
    return message.error('检验单已审核，不可删除！')
  }
  const { code, msg } = await post('/lis/LisRecord/doDelLisRecord', { recordLsh: store.currentData.lisRecord.recordLsh })
  if (code !== 0) return message.error(msg || '删除失败')
  message.success(msg || '删除成功')
  store.reset()
  sideListRef.value.getSideData()
  store.getOrderData()
}

// 打印
const onPrint = async (dylx) => {
  message.loading('打印中...')
  if (store.currentPatient.status !== '1') {
    const params = constructData()
    await post('/lis/LisRecord/doSaveLisRecord', params)
  }
  await new Promise((resolve) => setTimeout(resolve, 1000))
  const { code, msg, data } = await post('/lis/lisPrint/printLisRecord', { lsh: store.currentPatient.lsh, dylx })
  message.destroy()
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    const dataJson = JSON.parse(data)
    const chunkList = chunk(dataJson.printData.lisRecordItemList, 28)
    for (let i = 0; i < chunkList.length; i++) {
      printData.value = {
        ...dataJson,
        printData: {
          ...dataJson.printData,
          lisRecordItemList: chunkList[i]
        }
      }
      await new Promise((resolve) => setTimeout(resolve, 1000))
      setPrintSize('A5', 'landscape')
      printMe.value.$el.click()
      await new Promise((resolve) => setTimeout(resolve, 2000))
    }
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
  sideListRef.value.getSideData()
}
const onChangeRecordCode = async (type) => {
  const { code, msg, data } = await post('/lis/LisRecord/sampleNumberLastOrNext', {
    lisInstrumentId: store.currentInstrument.id,
    recordCode: store.recordCode,
    recordDate: store.recordDate,
    samplingTime: store.recordDate,
    type
  })
  if (code !== 0) return message.error(msg)
  store.reset(false)
  store.recordCode = data.recordCode
  data.applyId &&
    sideListRef.value.onSelect({
      recordCode: data.recordCode,
      lsh: data.applyId
    })
}

onUnmounted(() => {
  // 传false，不调用样本号，因为在没有选中任何患者时调用样本号会报错
  store.reset(false)
})

onMounted(() => {
  // 默认选中送检医师和送检时间
  onSelectApplyDoctor({ empId, empName })
  store.currentData.lisRecord.sendTime = dayjs().format('YYYY_MM_DD-HH_mm_ss')
})
const onSelectCode = async (row) => {
  store.barCode = row.barCode
  const { code, msg } = await post('/lis/LisRecord/doSelectedLisBarcode', {
    recordCode: store.recordCode,
    barcode: row.barCode,
    recordDate: store.recordDate
  })
  if (code !== 0) return message.error(msg)
  await store.getOrderData(2)
  onSave(false)
}
const getSearchParams = () => {
  const { pyjm, ...rest } = sideListParams.value
  if (!pyjm) {
    return rest
  }
  return rest
}
watch(
  () => store.currentData,
  () => {
    if (store.currentData.lisRecord) {
      store.currentData.lisRecord.testEmpName = store.currentData.lisRecord.testEmpName || empName
      store.currentData.lisRecord.testEmpId = store.currentData.lisRecord.testEmpId || empId
    }
  }
)
</script>
<style lang="less" scoped>
.full-disabled {
  :deep(.ant-btn) {
    filter: opacity(0.5);
    pointer-events: none;
  }
}
.history-card {
  transition: all 0.3s;
}
.history-expand {
  width: 56px !important;
  :deep(.ant-tabs) {
    visibility: hidden;
  }
}
.history-expand-btn {
  position: absolute;
  top: 4px;
  right: 12px;
  z-index: 99;
  padding: 8px;
  color: var(--primary-color);
  background-color: var(--secondary-color);
  border-radius: 8px;
  cursor: pointer;
}
</style>
